import 'package:interview/utils/logger.dart';

class StartupMonitor {
  final Map<String, int> _timestamps = {}; // 用于记录时间戳

  /// 标记一个启动阶段
  void mark(String stage) {
    final now = DateTime.now().millisecondsSinceEpoch;
    _timestamps[stage] = now;
    Logger.info("Marked stage: $stage at $now", tag: "StartupMonitor");
  }

  /// 计算两个阶段之间的耗时
  int duration(String startStage, String endStage) {
    if (_timestamps.containsKey(startStage) && _timestamps.containsKey(endStage)) {
      final duration = _timestamps[endStage]! - _timestamps[startStage]!;
      Logger.debug(
        "Duration from $startStage to $endStage: ${duration}ms",
        tag: "StartupMonitor",
      );
      return duration;
    }
    Logger.warn(
      "Cannot calculate duration, one or both stages are missing: $startStage, $endStage",
      tag: "StartupMonitor",
    );
    return -1; // 返回 -1 表示阶段缺失
  }

  /// 打印所有阶段的耗时
  void logResults() {
    Logger.info("Startup Monitor Results:", tag: "StartupMonitor");
    final stages = _timestamps.keys.toList();
    for (int i = 1; i < stages.length; i++) {
      duration(stages[i - 1], stages[i]);
    }
    if (stages.length > 1) {
      final totalDuration = duration(stages.first, stages.last);
      Logger.info("Total Startup Time: ${totalDuration}ms", tag: "StartupMonitor");
    }
  }
}
